package cm.mefobe.android.telecomcost.dialog;

import cm.mefobe.android.telecomcost.R;
import cm.mefobe.android.telecomcost.entities.TimePeriod;
import cm.mefobe.android.telecomcost.view.TimePeriodPickerView;
import cm.mefobe.android.telecomcost.view.TimePeriodRadioListView;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class TimePeriodPickerDialog extends Dialog {
		
	private TimePeriodPickerView _pickerView;
	private TimePeriodRadioListView periode_list_view;

	public TimePeriodPickerDialog(Context context, TimePeriodPickerView pickerView) {
		super(context);
		_pickerView = pickerView;		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("DaysPickerDialog", "Creating the dialog...");
		super.onCreate(savedInstanceState);

		setContentView(R.layout.periode_picker_dialog);
		setTitle("Select a period");

		periode_list_view = (TimePeriodRadioListView) findViewById(R.id.listViewPeriodes);
		
		periode_list_view.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				setSelectedPeriod();
			}
		});

		Log.i("DaysPickerDialog", "Dialog ohne bundle created....");
		periode_list_view.setDialog(this);
		periode_list_view.setAdapter(null);
	}

	protected void setSelectedPeriod() {
		if (_pickerView != null) {
			TimePeriod selectedPeriod = periode_list_view.getSelectedPeriod();
			if (selectedPeriod != null) {
				_pickerView.setPeriod(selectedPeriod);
				closeDialog();
			}	
			else {
				Log.i("DaysPickerDialog",
						"cannot set the period...no period selected");
			}
		} else {
			Log.i("DaysPickerDialog",
					"cannot set the period...no callback defined");
		}
	}

	protected void closeDialog() {
		Log.i("DaysPickerDialog", "closing the dialog");
		hide();
	}

	@Override
	public void show() {
		Log.i("DaysPickerDialog", "showing the dialog...");
		super.show();
		Log.i("DaysPickerDialog", "dialog on screen...");
	}

	@Override
	protected void onStart() {
		Log.i("DaysPickerDialog", "Starting the dialog...");
		super.onStart();
		Log.i("DaysPickerDialog", "dialog started...");
	}

	@Override
	protected void onStop() {
		Log.i("DaysPickerDialog", "Stopping the dialog...");
		super.onStop();
		Log.i("DaysPickerDialog", "dialog stopped...");
	}

	public void setPeriode(TimePeriod selectedPeriod) {
		if (_pickerView != null) {			
			if (selectedPeriod != null) {
				_pickerView.setPeriod(selectedPeriod);
				closeDialog();
			}	
			else {
				Log.i("DaysPickerDialog",
						"cannot set the period...no period selected");
			}
		} else {
			Log.i("DaysPickerDialog",
					"cannot set the period...no callback defined");
		}
	}
}
